<template>
	<view>
		<view class="tips color_fff size_12 align_c" :class="{ 'show':LoadJudge.loading }" @tap="getHistoryMsg">
			{{LoadJudge.loadText}}
		</view>
		<view class="box-1" id="list-box">
			<view class="talk-list" :style="{top:talkListTop+ 'px'}">
				<view v-for="(item,index) in talkList" :key="index" :id="`msg-${item.id}`">
					<text v-if="item.type==1"
						style="color: rgb(0,0,0,.4);text-align: center;margin: 16rpx 0 0 0;font-size: 26rpx;">
						{{timeChange(item.id)}}</text>
					<view class="item flex_col" :class=" item.type == 1 ? 'push':'pull' ">
						<image :src="item.pic" mode="aspectFill" class="pic"></image>
						<view class="content">
							<u-tooltip :buttons="['反馈问答']" direction="bottom" :showCopy="false"
								@click="tooltipClick(index,item)"></u-tooltip>
							{{item.content}}
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="box-2" :style="{bottom:box2Buttom+ 'px'}">
			<view class="flex_col">
				<view class="flex_grow">
					<input type="text" ref="chatInput" class="content" v-model="content" placeholder="请输入聊天内容"
						placeholder-style="color:#DDD;" :cursor-spacing="6" :adjust-position="adjustUp" />
				</view>
				<button class="send" @tap="send">发送</button>
			</view>
		</view>
		<u-notify ref="uNotify"></u-notify>
	</view>
</template>

<script>
	import {
		baiduUNITchat,
		sjfChat
	} from '../../services/chat/chat.js'
	export default {
		data() {
			return {
				token: "",
				talkList: [],
				LoadJudge: {
					rows: 20, //每页数量
					page: 1, //页码
					flag: true, // 请求开关
					loading: true, // 加载中
					loadText: '正在获取消息'
				},
				content: "",
				session_id: "",
				profilePic: "/static/unknownUser.jpg",
				adjustUp: true,
				windowHeight: "",
				talkListTop: 0,
				box2Buttom: 0
			}
		},
		mounted() {
			uni.getStorage({
				key: 'UserProfile',
				success: (res) => {
					this.profilePic = res.data.avatarUrl
				}
			})
			this.$nextTick(() => {
				this.getHistoryMsg();
			});
			wx.getSystemInfo({
				success: (res) => {
					this.windowHeight = res.windowHeight
				}
			})
			wx.onKeyboardHeightChange(res => {
				let keyboardHeight = res.height
				if (keyboardHeight != 0) {
					let query = wx.createSelectorQuery();
					query.select('.talk-list').boundingClientRect()
					query.exec((res2) => {
						if (res2[0].height > this.windowHeight) {
							this.adjustUp = true
							wx.offKeyboardHeightChange()
						} else {
							let trueChatHeight = this.windowHeight - 55 - keyboardHeight
							if (res2[0].height > trueChatHeight) {
								this.talkListTop = trueChatHeight - res2[0].height
							}
							this.box2Buttom = keyboardHeight
							this.adjustUp = false
						}
					})
				} else {
					this.talkListTop = 0
					this.box2Buttom = 0
				}
			})
			uni.getStorage({
				key: "token_xiaoyou",
				success: (res) => {
					this.token = res.data
				}
			})
		},
		methods: {
			// 获取历史消息
			getHistoryMsg() {
				if (!this.LoadJudge.flag) {
					return;
				}

				let get = async () => {
					this.hideLoadTips();
					this.LoadJudge.flag = false;
					let data = await this.joinHistoryMsg();

					console.log('----- 进入界面时读取缓存中的历史数据 -----');
					console.log(data);

					// 获取待滚动元素选择器，解决插入数据后，滚动条定位时使用
					let selector = '';

					if (this.LoadJudge.page > 1) {
						// 非第一页，则取历史消息数据的第一条信息元素
						selector = `#msg-${this.talkList[0].id}`;
					} else {
						// 第一页，则取当前消息数据的最后一条信息元素
						selector = `#msg-${data[data.length-1].id}`;
					}

					// 将获取到的消息数据合并到消息数组中
					this.talkList = [...data, ...this.talkList];

					// 数据挂载后执行
					this.$nextTick(() => {
						// 设置当前滚动的位置
						this.setPageScrollTo(selector);

						this.hideLoadTips(true);

						if (data.length < this.LoadJudge.rows) {
							// 当前消息数据条数小于请求要求条数时，则无更多消息，不再允许请求。
							// 可在此处编写无更多消息数据时的逻辑
						} else {
							this.LoadJudge.page++;
							setTimeout(() => {
								this.LoadJudge.flag = true;
							}, 200)
						}

					})
				}
				get();
			},
			// 拼接历史记录消息,后替换为请求历史记录接口
			joinHistoryMsg() {
				let join = () => {
					let arr
					try {
						arr = uni.getStorageSync('historyMsg');
					} catch (e) {

					}
					if (!arr) {
						arr = [{
							"id": new Date().getTime(),
							"content": "你好，我是小柚~",
							"type": 0,
							"pic": "/static/robot.jpg"
						}]
					}
					// arr.reverse();
					return arr;
				}

				return new Promise((done, fail) => {
					// 无数据请求接口，由 setTimeout 模拟，正式项目替换为 LoadJudge 即可。
					setTimeout(() => {
						let data = join();
						done(data);
					}, 100);
				})
			},
			// 设置页面滚动位置
			setPageScrollTo(selector) {
				let view = uni.createSelectorQuery().in(this).select(selector);
				view.boundingClientRect((res) => {
					uni.pageScrollTo({
						scrollTop: res.top - 30, // -30 为多显示出大半个消息的高度，示意上面还有信息。
						duration: 0
					});
				}).exec();
			},
			// 隐藏加载提示
			hideLoadTips(flag) {
				if (flag) {
					this.LoadJudge.loadText = '消息获取成功';
					setTimeout(() => {
						this.LoadJudge.loading = false;
					}, 300);
				} else {
					this.LoadJudge.loading = true;
					this.LoadJudge.loadText = '正在获取消息';
				}
			},

			// 发送信息
			async send() {
				if (!this.content.trim()) {
					uni.showToast({
						title: '请输入有效的内容',
						icon: 'none'
					})
					this.content = '';
					return;
				}
				uni.hideLoading();
				// 将当前发送信息 添加到消息列表。
				let data = {
					"id": new Date().getTime(),
					"content": this.content,
					"type": 1,
					"pic": this.profilePic
				}
				this.talkList.push(data);
				this.talkList.push({
					"id": new Date().getTime(),
					"content": "输入中...",
					"type": 0,
					"pic": "/static/robot.jpg"
				});
				this.$nextTick(() => {
					uni.pageScrollTo({
						scrollTop: 999999,
						duration: 100
					});
				})
				let queryData = {
					query: data.content,
					terminal_id: "xiaoyou" + this.token,
					log_id: "xiaoyou" + data.id,
					session_id: this.session_id
				}
				this.content = ""
				let answer = {}
				try {
					answer = await sjfChat(queryData.query)
					console.log(answer)
				} catch {
					this.$refs.uNotify.show({
						message: `SJF网络发生错误！`,
						type: "error"
					})
					this.talkList.pop()
					this.talkList.push({
						"id": new Date().getTime(),
						"content": "小柚不懂你的意思哦~",
						"type": 0,
						"pic": "/static/robot.jpg"
					});
					return
				}
				if (answer.success == "true") {
					answer = answer.content.answer
				} else {
					answer = await baiduUNITchat(queryData)
					console.log(answer)
					this.session_id = answer.session_id
					answer = answer.error_code == 0 ? answer.result.context.SYS_PRESUMED_HIST.slice(-1)[0] :
						"小柚不懂你的意思哦~"
				}
				// 百度机器人
				// let answer = (await baiduUNITchat(queryData)).result
				// this.session_id = answer.session_id
				// answer = answer.context.SYS_PRESUMED_HIST.slice(-1)[0] || "小柚不懂你的意思哦~"
				this.talkList.pop()
				this.talkList.push({
					"id": new Date().getTime(),
					"content": answer,
					"type": 0,
					"pic": "/static/robot.jpg"
				});
				this.$refs.uNotify.show({
					message: "若你不满意回答，可长按进行反馈",
					type: "warning",
					duration: "1400"
				})
				uni.setStorage({
					key: 'historyMsg',
					data: this.talkList,
				});
				this.$nextTick(() => {
					uni.pageScrollTo({
						scrollTop: 999999,
						duration: 100
					});
				})
			},
			tooltipClick(index, item) {
				let obj = {
					token: this.token,
					push: "",
					pull: "",
					pushPic: this.profilePic,
					pullPic: "/static/robot.jpg",
					rate: 0,
					feedback: ""
				}
				if (item.type == 1) {
					// 选中用户发送的，自动选下一条机器人回复的
					obj.push = this.talkList[index].content
					obj.pull = this.talkList[index + 1].content
				} else if (item.type == 0 && index != 0) {
					// 选中机器人回复的，自动选上一条用户发送的
					obj.push = this.talkList[index - 1].content
					obj.pull = this.talkList[index].content
				}
				if (index == 0) {
					this.$refs.uNotify.show({
						message: "此消息不可反馈",
						type: "error"
					})
				} else {
					uni.navigateTo({
						url: "../feedback/feedback",
						success: (res) => {
							res.eventChannel.emit('acceptDataFromOpenerPage', {
								data: obj
							})
						}
					})
				}
			},
			timeChange(date) {
				const time = new Date(date)
				let year = time.getFullYear()
				let mouth = time.getMonth() + 1
				let day = time.getDate()
				let hours = time.getHours()
				let minutes = time.getMinutes()
				let seconds = time.getSeconds()
				let nowtime = new Date()
				let nowmouth = nowtime.getMonth() + 1
				let nowday = nowtime.getDate()
				let t1 = (hours < 12) ? "上午" : "下午"
				let t2 = ""
				let t2Flag = false
				if (nowday == day && nowmouth == mouth) {
					t2 = ""
					t2Flag = true
				} else if (nowday == day - 1 && nowmouth == mouth) {
					t2 = "昨天"
					t2Flag = true
				}
				if (mouth < 10) {
					mouth = "0" + mouth
				}
				if (day < 10) {
					day = "0" + day
				}
				if (hours < 10) {
					hours = "0" + hours
				}
				if (minutes < 10) {
					minutes = "0" + minutes
				}
				if (seconds < 10) {
					seconds = "0" + seconds
				}
				if (t2Flag == false) {
					t2 = `${year}/${mouth}/${day}`
				}
				return `${t2}  ${t1}${hours}:${minutes}`
				// return `${year}/${mouth}/${day}  ${t1}${hours}:${minutes}`
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #F3F3F3;
		font-size: 28rpx;
	}

	.tooltip {
		position: absolute;
		height: 100%;
		width: 100%;
	}

	/* 加载数据提示 */
	.tips {
		position: fixed;
		left: 0;
		top: var(--window-top);
		width: 100%;
		z-index: 9;
		background-color: rgba(0, 0, 0, 0.15);
		height: 72rpx;
		line-height: 72rpx;
		transform: translateY(-80rpx);
		transition: transform 0.3s ease-in-out 0s;

		&.show {
			transform: translateY(0);
		}
	}

	.box-1 {
		width: 100%;
		height: auto;
		padding-bottom: 100rpx;
		box-sizing: content-box;

		/* 兼容iPhoneX */
		margin-bottom: 0;
		margin-bottom: constant(safe-area-inset-bottom);
		margin-bottom: env(safe-area-inset-bottom);
	}

	.box-2 {
		position: fixed;
		left: 0;
		width: 100%;
		height: auto;
		z-index: 2;
		border-top: #e5e5e5 solid 1px;
		box-sizing: content-box;
		background-color: #F3F3F3;

		/* 兼容iPhoneX */
		padding-bottom: 0;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);

		>view {
			padding: 0 20rpx;
			height: 100rpx;
		}

		.content {
			background-color: #fff;
			height: 64rpx;
			padding: 0 20rpx;
			border-radius: 32rpx;
			font-size: 28rpx;
		}

		.send {
			background-color: #42b983;
			color: #fff;
			height: 64rpx;
			margin-left: 20rpx;
			border-radius: 32rpx;
			padding: 0;
			width: 120rpx;
			line-height: 62rpx;

			&:active {
				background-color: #5fc496;
			}
		}
	}

	.talk-list {
		padding-bottom: 20rpx;
		position: relative;

		/* 消息项，基础类 */
		.item {
			position: relative;
			padding: 20rpx 20rpx 0 20rpx;
			align-items: flex-start;
			align-content: flex-start;
			color: #333;

			.pic {
				width: 92rpx;
				height: 92rpx;
				border-radius: 50%;
				border: #fff solid 1px;
			}

			.content {
				padding: 20rpx;
				border-radius: 4px;
				max-width: 500rpx;
				word-break: break-all;
				line-height: 52rpx;
				position: relative;
			}

			/* 收到的消息 */
			&.pull {
				.content {
					margin-left: 32rpx;
					background-color: #fff;

					&::after {
						content: '';
						display: block;
						width: 0;
						height: 0;
						border-top: 16rpx solid transparent;
						border-bottom: 16rpx solid transparent;
						border-right: 20rpx solid #fff;
						position: absolute;
						top: 30rpx;
						left: -18rpx;
					}
				}
			}

			/* 发出的消息 */
			&.push {
				/* 主轴为水平方向，起点在右端。使不修改DOM结构，也能改变元素排列顺序 */
				flex-direction: row-reverse;

				.content {
					margin-right: 32rpx;
					background-color: #a0e959;

					&::after {
						content: '';
						display: block;
						width: 0;
						height: 0;
						border-top: 16rpx solid transparent;
						border-bottom: 16rpx solid transparent;
						border-left: 20rpx solid #a0e959;
						position: absolute;
						top: 30rpx;
						right: -18rpx;
					}
				}
			}
		}
	}
</style>
